package com.thinkfit.jy.fragment;

import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.manager.DataManager;
import com.common.lib.mvp.contract.EmptyContract;
import com.common.lib.mvp.presenter.EmptyPresenter;
import com.common.lib.utils.LogUtil;
import com.inuker.bluetooth.library.Constants;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleReadResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.model.BleGattService;
import com.inuker.bluetooth.library.receiver.listener.BluetoothBondListener;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.inuker.bluetooth.library.utils.BluetoothUtils;
import com.inuker.bluetooth.library.utils.ByteUtils;
import com.thinkfit.jy.R;
import com.thinkfit.jy.adapter.BluetoothAdapter;
import com.thinkfit.jy.adapter.BondedBluetoothAdapter;
import com.thinkfit.jy.bluetooth.Bluetooth;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.MotionDataUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 蓝牙开关与设备列表界面
 */
// 192.168.31.145
public class BluetoothFragment extends BaseFragment<EmptyContract.Presenter> implements EmptyContract.View {

    private static final String TAG = "BluetoothFragment ------------->";
    private BluetoothAdapter mBluetoothAdapter;
    private BondedBluetoothAdapter mBondedBluetoothAdapter;
    private boolean mIsSearch;
    private boolean mIsBluetoothSwitchOpen;

    private Disposable countDownDisposable;

    private String mac = "";
    RecyclerView recyclerView, recyclerView2;

    private final BluetoothBondListener mBluetoothBondListener = new BluetoothBondListener() {
        @Override
        public void onBondStateChanged(String mac, int bondState) {
            LogUtil.LogE(TAG + mac + "-----Bindstate--" + bondState);
            if (bondState == Constants.BOND_BONDED) {
                getBondedBluetoothAdapter().setNewInstance(getBonderBluetoothDecicesFilter());
                getBluetoothAdapter().removeDevice(mac);
            }
            getBluetoothAdapter().notifyDataSetChanged();
        }
    };

    @SuppressLint("MissingPermission")
    public List<BluetoothDevice> getBonderBluetoothDecicesFilter() {
        List<BluetoothDevice> bondedBluetoothClassicDevices = BluetoothUtils.getBondedBluetoothClassicDevices();
        List<BluetoothDevice> bluetoothDeviceListfitter = new ArrayList<>();
        for (int i = 0; i < bondedBluetoothClassicDevices.size(); i++) {
            BluetoothDevice bluetoothDevice = bondedBluetoothClassicDevices.get(i);
            if (!TextUtils.isEmpty(bluetoothDevice.getName())) {
                if (BluetoothOrder.getInstance().isConnect()) {
                    if (bluetoothDevice.getAddress().equals(BluetoothOrder.getInstance().bluetoothMac)) {
                        bluetoothDeviceListfitter.add(0, bluetoothDevice);
                    } else {
                        bluetoothDeviceListfitter.add(bluetoothDevice);
                    }
                } else {
                    bluetoothDeviceListfitter.add(bluetoothDevice);
                }

            }
        }

        return bluetoothDeviceListfitter;
    }


    @NonNull
    @Override
    protected EmptyContract.Presenter onCreatePresenter() {
        return new EmptyPresenter(this);
    }

    @Override
    protected int getLayoutId() {
//        return DataManager.Companion.getInstance().getMainStyle() == 3 ? R.layout.fragment_bluetooth_setting_xm :
//                R.layout.fragment_bluetooth_setting;
        return R.layout.fragment_bluetooth_set;

    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        setViewsOnClickListener(R.id.tvBack, R.id.llBluetooth, R.id.tvSearch);

        recyclerView = view.findViewById(R.id.rvPairedDevice);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        getBondedBluetoothAdapter().onAttachedToRecyclerView(recyclerView);
        recyclerView.setAdapter(getBondedBluetoothAdapter());


        recyclerView2 = view.findViewById(R.id.rvSearchedDevice);
        layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView2.setLayoutManager(layoutManager);
        getBluetoothAdapter().onAttachedToRecyclerView(recyclerView2);
        recyclerView2.setAdapter(getBluetoothAdapter());

        Bluetooth.getInstance().registerBluetoothBondListener(mBluetoothBondListener);
        mIsSearch = false;

        // 初始化蓝牙适配器
        BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);

    }

    android.bluetooth.BluetoothAdapter bluetoothAdapter;
    AudioManager audioManager;

    @SuppressLint("MissingPermission")
    private BluetoothAdapter getBluetoothAdapter() {
        if (mBluetoothAdapter == null) {
            mBluetoothAdapter = new BluetoothAdapter(getActivity(), 0);
            mBluetoothAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    System.out.println(TAG + " 点击 : " + mBluetoothAdapter.getItem(position).getName());
                    System.out.println(TAG + " stopSearch ");
                    Bluetooth.getInstance().stopSearch();

                    SearchResult result = mBluetoothAdapter.getItem(position);
                    mBluetoothAdapter.changStatus(result.getAddress(), android.bluetooth.BluetoothAdapter.STATE_CONNECTING);
                    int state = Bluetooth.getConnectStatus(result.getAddress());
                    if (state != android.bluetooth.BluetoothAdapter.STATE_CONNECTED &&
                            state != android.bluetooth.BluetoothAdapter.STATE_CONNECTING) {
                        LogUtil.LogE(TAG + result.getAddress() + ", " + state);
                        System.out.println(TAG + " stopSearch " + result.device);
                        BluetoothDevice device = result.device;
//                    showToast(""+result.device.getType());
                        //配对
//                    try {
//                        Method method = BluetoothDevice.class.getMethod("createBond");
//                        method.invoke(result.device);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }

//                    showToast(result.device.getAddress()+"");
                        BluetoothOrder.getInstance().setBluetoothName(result.getName());
                        LogUtil.LogE(TAG + "bleAddress" + result.device.getAddress());
                        connectToDevice(device);
//                        connectBluetooth(result.device.getAddress(), device);


                    } else {
                        if (state == android.bluetooth.BluetoothAdapter.STATE_CONNECTED ||
                                state == android.bluetooth.BluetoothAdapter.STATE_CONNECTING) {
                            mBluetoothAdapter.changStatus(result.getAddress(), android.bluetooth.BluetoothAdapter.STATE_DISCONNECTED);
                            Bluetooth.getInstance().disconnect(result.getAddress());
                            HashMap<String, Object> map = new HashMap<>();
                            map.put(EventBusEvent.REFRESH_BLUETOOTH, null);
                            EventBus.getDefault().post(map);
                        }

                    }
                    getBluetoothAdapter().notifyDataSetChanged();
                }
            });
        }
        return mBluetoothAdapter;
    }

    @SuppressLint("MissingPermission")
    private BondedBluetoothAdapter getBondedBluetoothAdapter() {
        if (mBondedBluetoothAdapter == null) {
            mBondedBluetoothAdapter = new BondedBluetoothAdapter(getActivity(), 1);
            mBondedBluetoothAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    BluetoothDevice bean = mBondedBluetoothAdapter.getItem(position);
                    int state = Bluetooth.getConnectStatus(bean.getAddress());
                    LogUtil.LogE(TAG + bean.getAddress() + ", " + state);

                    if (state != android.bluetooth.BluetoothAdapter.STATE_CONNECTED &&
                            state != android.bluetooth.BluetoothAdapter.STATE_CONNECTING) {

//                        bluetoothDevice = mBondedBluetoothAdapter.getData().get(position);
//                        mBondedBluetoothAdapter.remove(position);
//                        mBondedBluetoothAdapter.addData(0,bluetoothDevice);

                        mBondedBluetoothAdapter.changStatus(bean.getAddress(), android.bluetooth.BluetoothAdapter.STATE_CONNECTING);
                        BluetoothOrder.getInstance().setBluetoothName(bean.getName());
                        LogUtil.LogE(TAG + "bleAddress" + bean.getAddress());
                        connectBluetooth(bean.getAddress(), null);
//                        Bluetooth.getInstance().connect(bean.getAddress(), options,new BleConnectResponse() {
//                            @Override
//                            public void onResponse(int code, BleGattProfile profile) {
//                                LogUtil.LogE(TAG+"code: " + code);
//                                if (code == REQUEST_SUCCESS) {
//                                    showToast(R.string.app_connect_success);
//                                    mac = bean.getAddress();
//                                    BluetoothOrder.getInstance().setBluetoothMac(mac);
//                                    mBondedBluetoothAdapter.changStatus(bean.getAddress(), android.bluetooth.BluetoothAdapter.STATE_CONNECTED);
//                                    DataManager.Companion.getInstance().saveBluetoothMac(bean.getAddress());
//                                } else {
//                                    showToast(R.string.app_connect_failed);
//                                    mBondedBluetoothAdapter.changStatus(bean.getAddress(), android.bluetooth.BluetoothAdapter.STATE_DISCONNECTED);
//                                }
//
//                                mBondedBluetoothAdapter.notifyDataSetChanged();
//                                LogUtil.LogE(TAG+"id"+profile.getServices().size());
//                                for (int i = 0; i < profile.getServices().size(); i++) {
//                                    Log.e(TAG+"id","id"+profile.getServices().get(i).toString());
//                                }
//
//                                if (profile.getServices().size()>0){
//                                    for (BleGattService bleGattService :profile.getServices()){
//                                        LogUtil.LogE(TAG+"UUID : "+bleGattService.getUUID());
//                                        //判断服务
//                                        if(bleGattService.getUUID().toString().startsWith("0000fff0")){
//                                            HashMap<String, Object> map = new HashMap<>();
//                                            map.put(EventBusEvent.BLUETOOTH_SUCCESS, 0);
//                                            EventBus.getDefault().post(map);
//
//                                            LogUtil.LogE(TAG+"   UUID111.size : "+bleGattService.getCharacters().size());
//                                            BluetoothOrder.getInstance().setBluetoothService(bleGattService.getUUID().toString());
//                                            //获取特征值
//                                            for (int i = 0;i<bleGattService.getCharacters().size();i++){
//                                                LogUtil.LogE(TAG+"BleGattCharacter   UUID : "+bleGattService.getCharacters().get(i).getUuid().toString());
//                                                if(bleGattService.getCharacters().get(i).getUuid().toString().startsWith("0000fff1")){
//                                                    bleNotify(bleGattService.getUUID().toString(),bleGattService.getCharacters().get(i).getUuid().toString());
////                                                    break;
//                                                }
//                                                if(bleGattService.getCharacters().get(i).getUuid().toString().startsWith("0000fff2")){
//                                                    String s = bleGattService.getCharacters().get(i).getUuid().toString();
//                                                    Observable.timer(500, TimeUnit.MILLISECONDS)
//                                                            .subscribe(new Observer<Long>() {
//                                                                @Override
//                                                                public void onSubscribe(Disposable d) {
//                                                                    countDownDisposable = d;
//                                                                }
//
//                                                                @Override
//                                                                public void onNext(Long aLong) {
//                                                                    //获取品牌和机型
//                                                                    bleWrite(bleGattService.getUUID().toString(),s
//                                                                            ,BluetoothOrder.EQUIPMENT_GET_BRAND_ID_TYPE_ID);
//                                                                }
//
//                                                                @Override
//                                                                public void onError(Throwable e) {
//                                                                    closeDiDisposable();
//                                                                }
//
//                                                                @Override
//                                                                public void onComplete() {
//                                                                    closeDiDisposable();
//                                                                }
//                                                            });
//
//
////                                                    break;
//                                                }
////                                                for (BleGattDescriptor bleGattDescriptor :bleGattService.getCharacters().get(i).getDescriptors()){
////                                                    LogUtil.LogE(TAG+"BleGattDescriptor   UUID : "+bleGattDescriptor.getmUuid());
////                                                }
//                                            }
//
//                                            break;
//                                        }
//                                    }
//                                }
//
//
//
////                                Bluetooth.getInstance().notify(mac, UUID.fromString("00001801-0000-1000-8000-00805f9b34fb")
////                                        , UUID.fromString("00002a04-0000-1000-8000-00805f9b34fb"), new BleNotifyResponse() {
////                                    @Override
////                                    public void onNotify(UUID service, UUID character, byte[] value) {
////
////                                        LogUtil.LogE(TAG+"notify"+value.length);
////
////                                    }
////
////                                    @Override
////                                    public void onResponse(int code) {
////                                        LogUtil.LogE(TAG+"response"+code);
////                                    }
////                                });
//
//
////                                Bluetooth.getInstance().read(mac, UUID.fromString("00001801-0000-1000-8000-00805f9b34fb")
////                                        , UUID.fromString("00002a04-0000-1000-8000-00805f9b34fb"), new BleReadResponse() {
////                                    @Override
////                                    public void onResponse(int code, byte[] data) {
////                                        LogUtil.LogE(TAG+code+"onresponese"+data.length);
////
////                                    }
////                                });
//
//
//                            }
//                        });


//                        Bluetooth.getInstance().read(mac, UUID.fromString("00001801-0000-1000-8000-00805f9b34fb")
//                                , UUID.fromString("00002a04-0000-1000-8000-00805f9b34fb"), new BleReadResponse() {
//                                    @Override
//                                    public void onResponse(int code, byte[] data) {
//                                        LogUtil.LogE(TAG+code+"onresponese"+data.length);
//
//                                    }
//                                });
//                        //读取数据
//                        Bluetooth.getInstance().read(mac, UUID.fromString("00001801-0000-1000-8000-00805f9b34fb"), UUID.fromString("charaterUUid"), new BleReadResponse() {
//                            @Override
//                            public void onResponse(int code, byte[] data) {
//
//                            }
//                        });


                    } else {
                        if (state == android.bluetooth.BluetoothAdapter.STATE_CONNECTED) {
                            mBondedBluetoothAdapter.changStatus(bean.getAddress(), android.bluetooth.BluetoothAdapter.STATE_DISCONNECTED);
                            Bluetooth.getInstance().disconnect(bean.getAddress());
                            BluetoothOrder.getInstance().setBluetoothName("");
                            HashMap<String, Object> map = new HashMap<>();
                            map.put(EventBusEvent.REFRESH_BLUETOOTH, null);
                            EventBus.getDefault().post(map);
                        }
                    }
                    mBondedBluetoothAdapter.notifyDataSetChanged();
                }
            });
        }
        return mBondedBluetoothAdapter;
    }

    // 连接设备（使用反射调用系统API）
    private void connectToDevice(BluetoothDevice device) {
        try {
            Class<?> profileClass = Class.forName("android.bluetooth.BluetoothA2dp");
            Method getProfileProxy = bluetoothAdapter.getClass().getMethod(
                    "getProfileProxy", Context.class, BluetoothProfile.ServiceListener.class, int.class);

            getProfileProxy.invoke(bluetoothAdapter, getActivity(), new BluetoothProfile.ServiceListener() {
                @Override
                public void onServiceConnected(int profile, BluetoothProfile proxy) {
                    try {
                        Method connectMethod = profileClass.getMethod("connect", BluetoothDevice.class);
                        connectMethod.invoke(proxy, device);
                        getActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "正在连接...", Toast.LENGTH_SHORT).show();
                            routeAudioToBluetooth(true);
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onServiceDisconnected(int profile) {}
            }, BluetoothProfile.A2DP);

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "连接失败", Toast.LENGTH_SHORT).show();
        }
    }

    // 音频路由控制
    private void routeAudioToBluetooth(boolean enable) {
        if (enable) {
            audioManager.startBluetoothSco();
            audioManager.setBluetoothScoOn(true);
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        } else {
            audioManager.stopBluetoothSco();
            audioManager.setBluetoothScoOn(false);
            audioManager.setMode(AudioManager.MODE_NORMAL);
        }
    }


    public void connectBluetooth(String address, BluetoothDevice device) {
        BleConnectOptions options = new BleConnectOptions.Builder()
                .setConnectRetry(2)  // 连接失败重连1
                .setConnectTimeout(10000)  // 连接超时10s
                .setServiceDiscoverRetry(2) //发现服务如果失败重连1次
                .setServiceDiscoverRetry(10000)  //发现服务超时20
                .build();

        Bluetooth.getInstance().connect(device.getAddress(), options, new BleConnectResponse() {
            @Override
            public void onResponse(int code, BleGattProfile profile) {
                LogUtil.LogE(TAG + "code: " + code);
                if (code == REQUEST_SUCCESS) {
                    showToast(R.string.app_connect_success);
                    if(device == null){
                        mac = address;
                    }else {
                        mac = device.getAddress();
                    }
                    BluetoothOrder.getInstance().setBluetoothMac(mac);
                    getBondedBluetoothAdapter().changStatus(mac, android.bluetooth.BluetoothAdapter.STATE_CONNECTED);
                    getBluetoothAdapter().changStatus(mac, android.bluetooth.BluetoothAdapter.STATE_CONNECTED);
                    DataManager.Companion.getInstance().saveBluetoothMac(mac);
                } else {
                    showToast(R.string.app_connect_failed);
                    getBondedBluetoothAdapter().changStatus(mac, android.bluetooth.BluetoothAdapter.STATE_DISCONNECTED);
                    getBluetoothAdapter().changStatus(mac, android.bluetooth.BluetoothAdapter.STATE_DISCONNECTED);
                }

                getBondedBluetoothAdapter().notifyDataSetChanged();
                getBluetoothAdapter().notifyDataSetChanged();
                LogUtil.LogE(TAG + " ddddddddddddddddddddddd  id" + profile.getServices().size());
                for (int i = 0; i < profile.getServices().size(); i++) {
                    LogUtil.LogE(TAG + "  ddddddddddddddddddddddd   id" + profile.getServices().get(i).toString());
                }


                if (profile.getServices().size()>0){
                    for (BleGattService bleGattService :profile.getServices()){
                        LogUtil.LogE(TAG+"  ddddddddddddddddddddddd  UUID : "+bleGattService.getUUID());
                        //判断服务
                        if(bleGattService.getUUID().toString().startsWith("0000fff0")){
                            HashMap<String, Object> map = new HashMap<>();
                            map.put(EventBusEvent.BLUETOOTH_SUCCESS, 0);
                            EventBus.getDefault().post(map);

                            LogUtil.LogE(TAG+"   ddddddddddddddddddddddd    UUID111.size : "+bleGattService.getCharacters().size());
                            BluetoothOrder.getInstance().setBluetoothService(bleGattService.getUUID().toString());
                            //获取特征值
                            for (int i = 0;i<bleGattService.getCharacters().size();i++){
                                LogUtil.LogE(TAG+"  ddddddddddddddddddddddd  BleGattCharacter   UUID : "+bleGattService.getCharacters().get(i).getUuid().toString());
                                if(bleGattService.getCharacters().get(i).getUuid().toString().startsWith("0000fff1")){
                                    bleNotify(bleGattService.getUUID().toString(),bleGattService.getCharacters().get(i).getUuid().toString());
//                                                    break;
                                }
                                if(bleGattService.getCharacters().get(i).getUuid().toString().startsWith("0000fff2")){
                                    String s = bleGattService.getCharacters().get(i).getUuid().toString();
                                    Observable.timer(500, TimeUnit.MILLISECONDS)
                                            .subscribe(new Observer<Long>() {
                                                @Override
                                                public void onSubscribe(Disposable d) {
                                                    countDownDisposable = d;
                                                }

                                                @Override
                                                public void onNext(Long aLong) {
                                                    //获取品牌和机型
                                                    bleWrite(bleGattService.getUUID().toString(),s
                                                            ,BluetoothOrder.EQUIPMENT_GET_BRAND_ID_TYPE_ID);
                                                }

                                                @Override
                                                public void onError(Throwable e) {
                                                    closeDiDisposable();
                                                }

                                                @Override
                                                public void onComplete() {
                                                    closeDiDisposable();
                                                }
                                            });


//                                                    break;
                                }
//                                                for (BleGattDescriptor bleGattDescriptor :bleGattService.getCharacters().get(i).getDescriptors()){
//                                                    LogUtil.LogE(TAG+"BleGattDescriptor   UUID : "+bleGattDescriptor.getmUuid());
//                                                }
                            }

                            break;
                        }
                    }
                }



//                                Bluetooth.getInstance().notify(mac, UUID.fromString("00001801-0000-1000-8000-00805f9b34fb")
//                                        , UUID.fromString("00002a04-0000-1000-8000-00805f9b34fb"), new BleNotifyResponse() {
//                                    @Override
//                                    public void onNotify(UUID service, UUID character, byte[] value) {
//
//                                        LogUtil.LogE(TAG+"notify"+value.length);
//
//                                    }
//
//                                    @Override
//                                    public void onResponse(int code) {
//                                        LogUtil.LogE(TAG+"response"+code);
//                                    }
//                                });
//
//
//                                Bluetooth.getInstance().read(mac, UUID.fromString("00001801-0000-1000-8000-00805f9b34fb")
//                                        , UUID.fromString("00002a04-0000-1000-8000-00805f9b34fb"), new BleReadResponse() {
//                                    @Override
//                                    public void onResponse(int code, byte[] data) {
//                                        LogUtil.LogE(TAG+code+"onresponese"+data.length);
//
//                                    }
//                                });


            }
        });
    }

    private void switchAudioOutputToHeadset() {
        AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
        audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        audioManager.startBluetoothSco();
        audioManager.setBluetoothScoOn(true);
        Toast.makeText(getActivity(), "已切换音频输出到蓝牙耳机", Toast.LENGTH_SHORT).show();
    }

    /**
     * 蓝牙通知
     * @param service
     * @param character
     */
    public void bleNotify(String service,String character){
        System.out.println(TAG+"  xxxxxxxxxxxxxxxxxxxxxxxxxxxxx  notify :  service : "+service);
        System.out.println(TAG+"  xxxxxxxxxxxxxxxxxxxxxxxxxxxxx  notify :  character : "+character);
        System.out.println(TAG+"  xxxxxxxxxxxxxxxxxxxxxxxxxxxxx  notify :  mac : "+mac);
        Bluetooth.getInstance().notify(mac, UUID.fromString(service)
                , UUID.fromString(character), new BleNotifyResponse() {
                    @Override
                    public void onNotify(UUID service, UUID character, byte[] value) {
                        System.out.println(TAG+"  xxxxxxxxxxxxxxxxxxxxxxxxxxxxx  notify111 :  service : "+service);
                        System.out.println(TAG+"  xxxxxxxxxxxxxxxxxxxxxxxxxxxxx  notify111 :  character : "+character);
                        System.out.println(TAG+"  xxxxxxxxxxxxxxxxxxxxxxxxxxxxx  notify111 :  value : "+ByteUtils.byteToString(value));
//                        MotionDataUtils.getInstance().motionDataResponse(value);
//                        BluetoothOrder.getInstance().bluetoothResponse(value);

                    }

                    @Override
                    public void onResponse(int code) {
                        System.out.println(TAG+" notify :  response"+code);

                    }
                });

    }

    public void bleIndicate(String service,String character){
        Bluetooth.getInstance().indicate(mac, UUID.fromString(service)
                , UUID.fromString(character), new BleNotifyResponse() {
                    @Override
                    public void onNotify(UUID service, UUID character, byte[] value) {
                        System.out.println(TAG+" ddddddddddddddddddddddd  indicate ");
                        BluetoothOrder.getInstance().bluetoothResponse(value);

                    }

                    @Override
                    public void onResponse(int code) {
                        System.out.println(TAG+" notify :  response"+code);

                    }
                });
    }


    /**
     * 读取蓝牙信息
     * @param service
     * @param character
     */
    public void bleRead(String service,String character){
        Bluetooth.getInstance().read(mac, UUID.fromString(service)
                , UUID.fromString(character), new BleReadResponse() {
                    @Override
                    public void onResponse(int code, byte[] data) {
                        LogUtil.LogE(TAG+"Read : "+code+"  onresponese : "+ByteUtils.byteToString(data));

                    }
                });
    }

    public void bleWrite(String service,String character,byte[] value){
        System.out.println(TAG+" ddddddddddddddddddddddd  bleWrite :  "+ByteUtils.byteToString(value));
        BluetoothOrder.getInstance().setBluetoothCharacter(character);
        Bluetooth.getInstance().write(mac, UUID.fromString(service)
                , UUID.fromString(character), value, new BleWriteResponse() {
                    @Override
                    public void onResponse(int code) {
                        LogUtil.LogE(TAG+"Write : "+code);
                    }
                });
    }

    public void onResume() {
        super.onResume();
        mIsBluetoothSwitchOpen = Bluetooth.getInstance().isBluetoothOpened();
        setImage(R.id.ivBluetoothSwitch, mIsBluetoothSwitchOpen ? R.drawable.app_switch_on :
                (DataManager.Companion.getInstance().getMainStyle() == 3 ? R.drawable.app_switch_off_xm : R.drawable.app_switch_off));
        if (Bluetooth.getInstance().isBluetoothOpened()) {
            search();
        }
        getBondedBluetoothAdapter().setNewInstance(getBonderBluetoothDecicesFilter());

    }


    @Override
    public void onStop() {
        super.onStop();
        System.out.println("ddddddddddddddddddddddd   BluetoothFragment ");
        DeviceTypeUtils.showBackButton(getContext().getApplicationContext());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llBluetooth:
                HashMap<String, Object> map = new HashMap<>();
                if (Bluetooth.getInstance().isBluetoothOpened()) {
                    mIsBluetoothSwitchOpen = false;
                    mIsSearch = false;
                    Bluetooth.getInstance().closeBluetooth();
                    setImage(R.id.ivBluetoothSwitch, (DataManager.Companion.getInstance().getMainStyle() == 3 ? R.drawable.app_switch_off_xm : R.drawable.app_switch_off));
                    getBluetoothAdapter().getData().clear();
                    getBluetoothAdapter().notifyDataSetChanged();
                    getBondedBluetoothAdapter().getData().clear();
                    getBondedBluetoothAdapter().notifyDataSetChanged();
                    setViewGone(R.id.tvSearch);
                    Bluetooth.getInstance().stopSearch();
                    map.put(EventBusEvent.BLUETOOTH_CHANGE, false);
                } else {
                    Bluetooth.getInstance().openBluetooth();
                    mIsBluetoothSwitchOpen = true;
                    setImage(R.id.ivBluetoothSwitch, R.drawable.app_switch_on);
                    v.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mIsSearch = false;
                            getBluetoothAdapter().getData().clear();
                            getBluetoothAdapter().notifyDataSetChanged();
                            search();
                        }
                    }, 3000);
                    setViewVisible(R.id.tvSearch);
                    map.put(EventBusEvent.BLUETOOTH_CHANGE, true);
                }
                EventBus.getDefault().post(map);
                break;
            case R.id.tvSearch:
                getBluetoothAdapter().getData().clear();
                getBluetoothAdapter().notifyDataSetChanged();
                mIsSearch = false;
                search();
                break;
            case R.id.tvBack:
                getParentFragmentManager().popBackStack();
                break;
        }
    }

    /**
     * 搜索设备
     */
    private void search() {
        if (mIsSearch) {
            return;
        }

        LogUtil.LogE(TAG+"search");
        SearchRequest request = new SearchRequest.Builder()
//                .searchBluetoothLeDevice(3000, 3)   // 先扫BLE设备3次，每次3s
//                .searchBluetoothClassicDevice(5000) // 再扫经典蓝牙5s
//                .searchBluetoothLeDevice(2000)// 再扫BLE设备2s
                .searchBluetoothLeDevice(3000)// 再扫BLE设备1s
                .build();
        //搜索列表
        Bluetooth.getInstance().search(request, searchResponse);
    }

    SearchResponse searchResponse = new SearchResponse() {
        @Override
        public void onSearchStarted() {
            setViewVisible(R.id.ivSearching);
            mIsSearch = true;
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onDeviceFounded(SearchResult device) {
            if (getView() == null) {
                return;
            }
            if (!mIsBluetoothSwitchOpen) {
                getBluetoothAdapter().getData().clear();
                getBluetoothAdapter().notifyDataSetChanged();
                return;
            }
            BluetoothDevice device1 = device.device;
            LogUtil.LogE(TAG+"onDeviceFounded: " + device1.getBluetoothClass()+"........."+device1.getType()+"...");
            if (device.device.getBondState() != Constants.BOND_BONDED) {
//                    LogUtil.LogE(TAG + "name:"+device1.getAlias().toString());
//                        device.device.getBluetoothClass().getMajorDeviceClass().

                if (TextUtils.isEmpty(device.device.getName())){
                    return;
                }

                getBluetoothAdapter().addData(device);
                getBluetoothAdapter().notifyDataSetChanged();
            }


//                //解除配对
//                try {
//                    Method removeBondMethod = BluetoothDevice.class.getMethod("removeBond");
//                    removeBondMethod.invoke(BluetoothDevice device);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
        }

        @Override
        public void onSearchStopped() {
            if (getView() == null) {
                return;
            }
            setViewGone(R.id.ivSearching);
            mIsSearch = false;
        }

        @Override
        public void onSearchCanceled() {
            if (getView() == null) {
                return;
            }
            setViewGone(R.id.ivSearching);
            mIsSearch = false;
        }
    };
    public void closeDiDisposable(){
        if(countDownDisposable != null && countDownDisposable.isDisposed()){
            countDownDisposable.dispose();
            countDownDisposable = null;
        }
    }

    public void onDestroyView() {
        super.onDestroyView();
        closeDiDisposable();
        Bluetooth.getInstance().stopSearch();
        Bluetooth.getInstance().unregisterBluetoothBondListener(mBluetoothBondListener);
    }
}
